package it.vetlab;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class VetLabService {

	private static VetLabService instance;

	public static VetLabService getInstance() {
		if (instance == null) {
			instance = new VetLabService();
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	public User getUserByCookie(String cookie) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(User.class);
			query.declareParameters("String myCookie");
			query.setFilter("cookie == myCookie");
			List<User> users = (List<User>) query.execute(cookie);
			return users.isEmpty() ? null : users.get(0);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public User getUserByEmail(String email) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(User.class);
			query.declareParameters("String myEmail");
			query.setFilter("email == myEmail");
			List<User> users = (List<User>) query.execute(email);
			return users.isEmpty() ? null : users.get(0);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<User> listEnabledAdminUsers(PersistenceManager pm) {
		Query query = pm.newQuery("select from " + User.class.getName()
				+ " where admin == true && enabled == true");
		// query.setOrdering("lastName ASC, firstName ASC");
		return (List<User>) query.execute();
	}

	public int countEnabledAdminUsers() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery("select count(email) from "
					+ User.class.getName()
					+ " where enabled == true && admin == true");
			return (Integer) query.execute();
		} finally {
			pm.close();
		}
	}

	public User saveUser(User user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			return pm.makePersistent(user);
		} finally {
			pm.close();
		}
	}
}
